<template>
  <div class="register-page">
    <Header />
    
    <div class="register-container">
      <!-- 左侧宣传区域 - 与登录页相同但内容略有不同 -->
      <div class="register-left">
        <div class="content-wrapper">
          <h1>加入智能管理系统</h1>
          <p class="subtitle">开启高效管理之旅</p>
          <p class="description">
            注册成为我们的用户，<br>
            体验全方位的智能管理解决方案。
          </p>
          <div class="features">
            <div class="feature-item">
              <i class="icon">✓</i>
              <span>7x24小时技术支持</span>
            </div>
            <div class="feature-item">
              <i class="icon">✓</i>
              <span>数据实时备份</span>
            </div>
            <div class="feature-item">
              <i class="icon">✓</i>
              <span>专属客户经理</span>
            </div>
          </div>
        </div>
        <div class="background-overlay"></div>
        <div class="background-image"></div>
      </div>
      
      <!-- 右侧注册区域 - 比登录表单更丰富 -->
      <div class="register-right">
        <div class="register-card">
          <div class="register-header">
            <h2>用户注册</h2>
            <p>创建您的账号</p>
          </div>
          
          <div class="register-body">
            <form @submit.prevent="handleSubmit">
              <div class="form-group">
                <label for="username">用户名</label>
                <div class="input-wrapper">
                  <i class="icon">👤</i>
                  <input 
                    type="text" 
                    id="username" 
                    v-model="form.username" 
                    class="form-control" 
                    :class="{ 'is-invalid': errors.username }"
                    placeholder="请输入用户名(4-16位字母或数字)"
                    required
                  >
                </div>
                <div class="invalid-feedback" v-if="errors.username">
                  {{ errors.username }}
                </div>
              </div>
              
              <div class="form-group">
                <label for="password">密码</label>
                <div class="input-wrapper">
                  <i class="icon">🔒</i>
                  <input 
                    type="password" 
                    id="password" 
                    v-model="form.password" 
                    class="form-control" 
                    :class="{ 'is-invalid': errors.password }"
                    placeholder="请输入密码(至少6位)"
                    required
                  >
                </div>
                <div class="password-strength">
                  <div class="strength-bar" :class="passwordStrengthClass"></div>
                  <span class="strength-text">{{ passwordStrengthText }}</span>
                </div>
                <div class="invalid-feedback" v-if="errors.password">
                  {{ errors.password }}
                </div>
              </div>
              
              <div class="form-group">
                <label for="confirmPassword">确认密码</label>
                <div class="input-wrapper">
                  <i class="icon">🔒</i>
                  <input 
                    type="password" 
                    id="confirmPassword" 
                    v-model="form.confirmPassword" 
                    class="form-control" 
                    :class="{ 'is-invalid': errors.confirmPassword }"
                    placeholder="请再次输入密码"
                    required
                  >
                </div>
                <div class="invalid-feedback" v-if="errors.confirmPassword">
                  {{ errors.confirmPassword }}
                </div>
              </div>
              
              <div class="form-group">
                <label for="email">电子邮箱</label>
                <div class="input-wrapper">
                  <i class="icon">✉️</i>
                  <input 
                    type="email" 
                    id="email" 
                    v-model="form.email" 
                    class="form-control" 
                    :class="{ 'is-invalid': errors.email }"
                    placeholder="请输入常用邮箱"
                    required
                  >
                </div>
                <div class="invalid-feedback" v-if="errors.email">
                  {{ errors.email }}
                </div>
              </div>
              
              <div class="form-group">
                <label for="nickname">昵称(可选)</label>
                <div class="input-wrapper">
                  <i class="icon">😊</i>
                  <input 
                    type="text" 
                    id="nickname" 
                    v-model="form.nickname" 
                    class="form-control" 
                    :class="{ 'is-invalid': errors.nickname }"
                    placeholder="请输入昵称"
                  >
                </div>
                <div class="invalid-feedback" v-if="errors.nickname">
                  {{ errors.nickname }}
                </div>
              </div>
              
              <!-- 图片验证码区域 -->
              <div class="form-group">
                <label for="code">验证码</label>
                <div class="captcha-container">
                  <div class="input-wrapper">
                    <i class="icon">🔐</i>
                    <input 
                      type="text" 
                      id="code" 
                      v-model="form.code" 
                      class="form-control" 
                      :class="{ 'is-invalid': errors.code }"
                      placeholder="请输入验证码"
                      required
                      maxlength="6"
                      style="width:76%"
                    >
                  </div>
                  <div class="captcha-image" @click="refreshCaptcha">
                    <img v-if="captcha.img" :src="captcha.img" alt="验证码">
                    <span v-else>加载验证码...</span>
                  </div>
                </div>
                <div class="invalid-feedback" v-if="errors.code">
                  {{ errors.code }}
                </div>
              </div>
              
              <div class="form-group terms-group">
                <div class="form-check">
                  <input type="checkbox" id="agree" v-model="form.agree" class="form-check-input" required>
                  <label for="agree" class="form-check-label">
                    我已阅读并同意<a href="/terms" target="_blank">《用户协议》</a>和<a href="/privacy" target="_blank">《隐私政策》</a>
                  </label>
                </div>
                <div class="invalid-feedback" v-if="errors.agree">
                  {{ errors.agree }}
                </div>
              </div>
              
              <div class="form-group">
                <button type="submit" class="btn btn-register" :disabled="loading">
                  <span v-if="loading" class="spinner-border spinner-border-sm" role="status"></span>
                  立即注册
                </button>
              </div>
              
              <div class="login-link">
                已有账号? <router-link to="/login">立即登录</router-link>
              </div>
              
              <div class="social-login">
                <p class="divider"><span>或使用第三方账号注册</span></p>
                <div class="social-icons">
                  <a href="#" class="social-icon wechat"><i>微信</i></a>
                  <a href="#" class="social-icon qq"><i>QQ</i></a>
                  <a href="#" class="social-icon weibo"><i>微博</i></a>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    
    <Footer />
  </div>
</template>

<script>
import Header from '@/components/Header'
import Footer from '@/components/Footer'
import { register, getCaptchaImage  } from '@/api/user'

export default {
  name: 'Register',
  components: {
    Header,
    Footer
  },
  data() {
    return {
      form: {
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        nickname: '',
        code: '',
        agree: false
      },
      captcha: {
        img: '',
        uuid: ''
      },
      errors: {},
      loading: false,
      codeCountdown: 0,
      countdownInterval: null
    }
  },
  computed: {
    passwordStrength() {
      if (!this.form.password) return 0
      let strength = 0
      
      // 长度评分
      if (this.form.password.length >= 6) strength += 1
      if (this.form.password.length >= 8) strength += 1
      
      // 复杂度评分
      if (/[A-Z]/.test(this.form.password)) strength += 1
      if (/[0-9]/.test(this.form.password)) strength += 1
      if (/[^A-Za-z0-9]/.test(this.form.password)) strength += 1
      
      return Math.min(strength, 4) // 最大为4
    },
    passwordStrengthClass() {
      return [
        'strength-' + this.passwordStrength,
        { 'invalid': this.errors.password }
      ]
    },
    passwordStrengthText() {
      if (!this.form.password) return ''
      const texts = ['非常弱', '弱', '中等', '强', '非常强']
      return texts[this.passwordStrength]
    }
  },
  created() {
    this.refreshCaptcha()
  },
  methods: {
    validateForm() {
      this.errors = {}
      let isValid = true
      
      // 用户名验证
      if (!this.form.username) {
        this.errors.username = '请输入用户名'
        isValid = false
      } else if (!/^[a-zA-Z0-9]{4,16}$/.test(this.form.username)) {
        this.errors.username = '用户名应为4-16位字母或数字'
        isValid = false
      }
      
      // 密码验证
      if (!this.form.password) {
        this.errors.password = '请输入密码'
        isValid = false
      } else if (this.form.password.length < 6) {
        this.errors.password = '密码长度不能小于6位'
        isValid = false
      }
      
      // 确认密码验证
      if (this.form.password !== this.form.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致'
        isValid = false
      }
      
      // 邮箱验证
      if (!this.form.email) {
        this.errors.email = '请输入邮箱'
        isValid = false
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.form.email)) {
        this.errors.email = '请输入有效的邮箱地址'
        isValid = false
      }
      
      // 验证码验证
      if (!this.form.code) {
        this.errors.code = '请输入验证码'
        isValid = false
      }
      
      // 协议同意验证
      if (!this.form.agree) {
        this.errors.agree = '请阅读并同意用户协议和隐私政策'
        isValid = false
      }
      
      return isValid
    },
     async refreshCaptcha() {
      try {
        const res = await getCaptchaImage()
        if (res.code === 200) {
          this.captcha.img = 'data:image/png;base64,' + res.img
          this.captcha.uuid = res.uuid
          this.form.uuid = res.uuid
        } else {
          this.$notify.error({
            title: '错误',
            message: '验证码获取失败'
          })
        }
      } catch (error) {
        console.error('验证码加载错误:', error)
        this.$notify.error({
          title: '错误',
          message: '验证码加载失败，请刷新页面重试'
        })
      }
    },
    async sendCode() {
      if (!this.form.email) {
        this.$notify.error({
          title: '错误',
          message: '请先输入邮箱地址'
        })
        return
      }
      
      try {
        await sendVerificationCode({ email: this.form.email })
        this.$notify.success({
          title: '成功',
          message: '验证码已发送至您的邮箱'
        })
        
        // 开始倒计时
        this.codeCountdown = 60
        this.countdownInterval = setInterval(() => {
          if (this.codeCountdown > 0) {
            this.codeCountdown--
          } else {
            clearInterval(this.countdownInterval)
          }
        }, 1000)
      } catch (error) {
        this.$notify.error({
          title: '错误',
          message: error.response?.data?.message || '验证码发送失败'
        })
      }
    },
    async handleSubmit() {
      if (!this.validateForm()) return
      
      this.loading = true
      
      try {
        const submitData = {
          ...this.form,
          uuid: this.captcha.uuid
        }
        await register(submitData)
        
        this.$notify({
          title: '成功',
          message: '注册成功，请登录',
          type: 'success'
        })
        
        this.$router.push('/login')
      } catch (error) {
        if (error.response && error.response.status === 400) {
          this.errors = error.response.data.errors || {}
          this.$notify.error({
            title: '错误',
            message: error.response.data.message || '注册失败'
          })
          // 验证码错误时刷新验证码
          if (error.response.data.message.includes('验证码')) {
            this.refreshCaptcha()
          }
        } else {
          this.$notify.error({
            title: '错误',
            message: '网络错误，请稍后重试'
          })
        }
      } finally {
        this.loading = false
      }
    }
  },
  beforeDestroy() {
    if (this.countdownInterval) {
      clearInterval(this.countdownInterval)
    }
  }
}
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

.register-container {
  display: flex;
  flex: 1;
  min-height: calc(100vh - 120px);
}

/* 左侧区域样式 - 与登录页类似但颜色不同 */
.register-left {
  flex: 1;
  position: relative;
  min-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  overflow: hidden;
}

.content-wrapper {
  position: relative;
  z-index: 3;
  max-width: 600px;
  padding: 40px;
  text-align: center;
}

.register-left h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  font-weight: 600;
  line-height: 1.2;
}

.register-left .subtitle {
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  color: rgba(255, 255, 255, 0.9);
}

.register-left .description {
  font-size: 1.1rem;
  line-height: 1.6;
  margin-bottom: 2rem;
  opacity: 0.9;
}

.features {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 2rem;
}

.feature-item {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  padding: 10px 20px;
  border-radius: 50px;
  backdrop-filter: blur(5px);
}

.feature-item .icon {
  margin-right: 8px;
  font-weight: bold;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url('https://images.unsplash.com/photo-1551288049-bebda4e38f71?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80');
  background-size: cover;
  background-position: center;
  z-index: 1;
}

.background-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #6e48aa 0%, #9d50bb 100%);
  opacity: 0.85;
  z-index: 2;
}

/* 右侧注册区域样式 - 比登录页更丰富 */
.register-right {
  width: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 40px;
  background-color: white;
  box-shadow: -5px 0 15px rgba(0, 0, 0, 0.05);
}

.register-card {
  width: 100%;
  max-width: 400px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  font-size: 1.8rem;
  color: #6e48aa;
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.register-header p {
  color: #7f8c8d;
  font-size: 0.95rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #2c3e50;
  font-size: 0.95rem;
}

.input-wrapper {
  position: relative;
}

.input-wrapper .icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 1.1rem;
}

.form-control {
  width: 100%;
  padding: 12px 15px 12px 45px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background-color: #f9f9f9;
}

.form-control:focus {
  border-color: #6e48aa;
  box-shadow: 0 0 0 3px rgba(110, 72, 170, 0.1);
  outline: none;
  background-color: white;
}

.is-invalid {
  border-color: #e74c3c;
}

.invalid-feedback {
  color: #e74c3c;
  font-size: 0.85rem;
  margin-top: 0.25rem;
}

/* 密码强度指示器 */
.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
}

.strength-bar {
  height: 4px;
  border-radius: 2px;
  flex-grow: 1;
  margin-right: 10px;
  background-color: #e0e0e0;
  overflow: hidden;
  position: relative;
}

.strength-bar::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 0;
  transition: width 0.3s ease, background-color 0.3s ease;
}

.strength-0::after {
  width: 25%;
  background-color: #e74c3c;
}

.strength-1::after {
  width: 25%;
  background-color: #e74c3c;
}

.strength-2::after {
  width: 50%;
  background-color: #f39c12;
}

.strength-3::after {
  width: 75%;
  background-color: #3498db;
}

.strength-4::after {
  width: 100%;
  background-color: #2ecc71;
}

.strength-text {
  font-size: 0.8rem;
  color: #7f8c8d;
}

.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-image {
  width: 120px;
  height: 46px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  background-color: #f5f5f5;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.captcha-image:hover {
  border-color: #6e48aa;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.captcha-image span {
  color: #7f8c8d;
  font-size: 0.8rem;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .captcha-container {
    flex-direction: column;
  }
  
  .captcha-image {
    width: 100%;
    height: 45px;
    margin-top: 10px;
  }
}

.btn-send-code {
  flex-shrink: 0;
  padding: 0 15px;
  height: 46px;
  background-color: #6e48aa;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-send-code:hover {
  background-color: #9d50bb;
}

.btn-send-code:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

/* 协议条款样式 */
.terms-group {
  margin-top: 1.5rem;
}

.terms-group .form-check-label {
  font-size: 0.9rem;
  color: #7f8c8d;
}

.terms-group a {
  color: #6e48aa;
  text-decoration: none;
}

.terms-group a:hover {
  text-decoration: underline;
}

/* 注册按钮样式 */
.btn-register {
  width: 100%;
  padding: 12px;
  background-color: #6e48aa;
  border: none;
  border-radius: 6px;
  color: white;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(110, 72, 170, 0.2);
  margin-top: 1rem;
}

.btn-register:hover {
  background-color: #9d50bb;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(110, 72, 170, 0.3);
}

.btn-register:active {
  transform: translateY(0);
}

.btn-register:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 登录链接样式 */
.login-link {
  text-align: center;
  margin-top: 1.5rem;
  color: #7f8c8d;
  font-size: 0.95rem;
}

.login-link a {
  color: #6e48aa;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s;
}

.login-link a:hover {
  color: #9d50bb;
  text-decoration: underline;
}

/* 社交登录样式 */
.social-login {
  margin-top: 2rem;
  text-align: center;
}

.divider {
  display: flex;
  align-items: center;
  color: #7f8c8d;
  font-size: 0.9rem;
  margin-bottom: 1rem;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  border-bottom: 1px solid #e0e0e0;
}

.divider::before {
  margin-right: 1rem;
}

.divider::after {
  margin-left: 1rem;
}

.social-icons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.social-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-decoration: none;
  transition: all 0.3s ease;
}

.social-icon i {
  font-style: normal;
  font-size: 0.8rem;
}

.social-icon.wechat {
  background-color: #07C160;
}

.social-icon.qq {
  background-color: #12B7F5;
}

.social-icon.weibo {
  background-color: #E6162D;
}

.social-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

/* 响应式设计 */
@media (max-width: 992px) {
  .register-container {
    flex-direction: column;
  }
  
  .register-left {
    padding: 60px 20px;
    min-height: auto;
  }
  
  .register-right {
    width: 100%;
    padding: 40px 20px;
    box-shadow: none;
  }
}

@media (max-width: 576px) {
  .register-left h1 {
    font-size: 2rem;
  }
  
  .register-left .subtitle {
    font-size: 1.2rem;
  }
  
  .features {
    flex-direction: column;
    gap: 10px;
  }
  
  .captcha-container {
    flex-direction: column;
  }
  
  .btn-send-code {
    width: 100%;
    margin-top: 10px;
  }
  
  .social-icons {
    gap: 10px;
  }
}
</style>